﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Logic.ClarizenObjects;
using Logic;
using Logic.ClarizenSvc;
using ClarizenGadget.Models;
using BLL;

namespace ClarizenGadget.Controllers
{
    public class DocumentsController : Controller
    {
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult _DocumentsTab(string taskID)
        //{
        //    var queryApi = new QueryComponent();
        //    return View(new DocumentViewModel{
        //        AuthorizedGoogle = Users.GetCurrentUser().IsGoogleAuthorized,
        //        DocumentTypes = queryApi.GetListByTypeName("DocumentType", useCache: true),
        //    });
        //}

        public ActionResult _List(string taskID)
        {
            var queryApi = new QueryComponent();
            var wi = new WorkItem { ID = new Logic.ClarizenSvc.EntityId { TypeName = "WorkItem", Value = taskID } };
            var docs = wi.GetDocuments();

            return View(docs);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Document doc)
        {
            try
            {
                var messages = new List<BaseMessage>();

                if (string.IsNullOrEmpty(doc.ID.Value))
                {
                    doc.ID.Value = Guid.NewGuid().ToString();
                    messages.Add(new CreateMessage { Entity = doc.ToGenericEntity() });

                    if (!string.IsNullOrEmpty(doc.TaskID))
                    {

                        var link = new GenericEntity
                        {
                            Id = new EntityId
                            {
                                TypeName = "AttachmentLink",
                            },
                            Values = new FieldValue[]{
                                new FieldValue{FieldName="WorkItem", Value = new EntityId{TypeName="WorkItem", Value=doc.TaskID}},
                                new FieldValue{FieldName="Document", Value = doc.ID}
                            }
                        };
                        messages.Add(new CreateMessage { Entity = link });
                    }
                }
                else
                {
                    messages.Add(new UpdateMessage { Entity = doc.ToGenericEntity() });
                }

                byte[] buf = null;
                if (Request.Files.Count > 0)
                {
                    var file = Request.Files[0];
                    buf = new byte[file.ContentLength];
                    file.InputStream.Read(buf, 0, file.ContentLength);
                }

                var upload = new UploadMessage
                {
                    DocumentId = doc.ID,
                    FileInformation = new FileInformation
                    {
                        Content = buf,
                        Url = doc.Url,
                        SubType = doc.Type,
                        FileName = doc.Name,
                        Storage = doc.Type == "Path"? Storage.Link: doc.Type == "Upload"? Storage.Server: Storage.Url,
                    }
                };
                
                messages.Add(upload);

                new QueryComponent().Execute(messages.ToArray());

                doc = Document.Intitialize<Document>(new QueryComponent().RetrieveEntity(doc.ID, BaseObject.GetFields<Document>()));

                return Json(new GadgetResponse<Object> { Status = GadgetResponseStatus.Success, Data = doc });
            }
            catch (Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }


        public ActionResult Delete(string linkID, string docID)
        {
            try
            {
                var messages = new List<BaseMessage>();
                messages.Add(new DeleteMessage { Id = new EntityId { TypeName = "Document", Value = docID } });
                //if(!string.IsNullOrEmpty(linkID))
                //    messages.Add(new DeleteMessage { Id = new EntityId { TypeName = "AttachmentLink", Value = linkID } });
                new QueryComponent().Execute(messages.ToArray());

                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Success, Data = true });
            }
            catch(Exception e)
            {
                return Json(new GadgetResponse<Boolean> { Status = GadgetResponseStatus.Error, ErrorMessage = e.Message });
            }
        }
        
    }
}
